package robuin.ioio.config;

//import robuin.ioio.config.IOIOSeek.SlowAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import robuin.ioio.config.R;
import ioio.lib.api.PwmOutput;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.api.exception.OutOfResourceException;
import ioio.lib.util.android.IOIOActivity;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;

	public class pwmOutput extends IOIOActivity{
		private List<SeekBar> listSeekBar_ = new ArrayList<SeekBar>();
		private List<EditText> listEditText_ = new ArrayList<EditText>();
		// only 9 at a time
		private List<Integer> pins = new ArrayList<Integer>(
				Arrays.asList(3,4,5,6,7,10,11,12,13));
		private IOIOThread ioioThread;
	    private TextView mStatus;
	    
	    class CustomTextWatcher implements TextWatcher{
	    	private EditText editText;
	    	
	    	public CustomTextWatcher(EditText e){
	    		editText = e;
	    	}
	    	@Override
			public void afterTextChanged(Editable arg0) {
	    		try {
		    		int newValue = Integer.parseInt(arg0.toString());
					int location = listEditText_.indexOf(editText);
					ioioThread.modify(location, newValue);
	    		}catch(NumberFormatException e){
	    			Log.d("afterTextChanged", e.getMessage());
	    		}
	    	}
	    	@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }	
	    }

	    class IOIOThread extends BaseIOIOLooper {
	    	private List<PwmOutput> listPwmOutputs_ = new ArrayList<PwmOutput>();

	    	public void modify(int location, int newValue) {
	    		if(listPwmOutputs_.size() <= location || newValue <= 0)
	    			return;
	    		
	    		PwmOutput pwmOutput = listPwmOutputs_.get(location);
	    		pwmOutput.close();
	    		listPwmOutputs_.remove(location);
	    		
	    		try {
					pwmOutput = ioio_.openPwmOutput(pins.get(location), newValue);
					listPwmOutputs_.add(location, pwmOutput);
					enableUi(true, location);
				} catch (ConnectionLostException e) {
					enableUi(false, location);
				}
	    	}
			
	    	@Override
			public void setup() throws ConnectionLostException {
				try {
					for(int i = 0; i < pins.size(); i++)
						listPwmOutputs_.add(ioio_.openPwmOutput(pins.get(i), Integer.parseInt(listEditText_.get(i).getText().toString())));
					
					enableUi(true);
				} catch (ConnectionLostException e) {
					enableUi(false);
					throw e;
				} catch(OutOfResourceException e){
					Log.d("PWM", "Out of resource:" + e.getMessage());
				}
			}
			
	    	@Override
			public void loop() throws ConnectionLostException {
				try {
					int minSize = listSeekBar_.size() < listPwmOutputs_.size() ? listSeekBar_.size() : listPwmOutputs_.size();
					
					for(int i = 0; i < minSize; i++)
						listPwmOutputs_.get(i).setDutyCycle(listSeekBar_.get(i).getProgress());
					
					Thread.sleep(100);
				} catch (InterruptedException e) {
					ioio_.disconnect();
				} catch (ConnectionLostException e) {
					enableUi(false);
					throw e;
				}
			}
	    	
	    	@Override
	    	public void disconnected(){
	    		for(int i = 0; i < listPwmOutputs_.size(); i++)
	    			listPwmOutputs_.get(i).close();
	    	}
		}
	    
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);

	        Intent intent = getIntent();
	        String message = intent.getStringExtra(IOIOConfig.EXTRA_MESSAGE);
	        
	        setContentView(R.layout.pwmoutput);

	        listSeekBar_.add((SeekBar)findViewById(R.id.SeekBar1));
	        listSeekBar_.add((SeekBar)findViewById(R.id.SeekBar2));
	        listSeekBar_.add((SeekBar)findViewById(R.id.SeekBar3));
	        listSeekBar_.add((SeekBar)findViewById(R.id.SeekBar4));
	        listSeekBar_.add((SeekBar)findViewById(R.id.SeekBar5));
	        listSeekBar_.add((SeekBar)findViewById(R.id.SeekBar6));
	        listSeekBar_.add((SeekBar)findViewById(R.id.SeekBar7));
	        listSeekBar_.add((SeekBar)findViewById(R.id.SeekBar8));
	        listSeekBar_.add((SeekBar)findViewById(R.id.SeekBar9));
	        //listSeekBar_.add((SeekBar)findViewById(R.id.SeekBar10));
	        
	        listEditText_.add(getEditTextWithCustomTextWatcher(R.id.editText1));
	        listEditText_.add(getEditTextWithCustomTextWatcher(R.id.editText2));
	        listEditText_.add(getEditTextWithCustomTextWatcher(R.id.editText3));
	        listEditText_.add(getEditTextWithCustomTextWatcher(R.id.editText4));
	        listEditText_.add(getEditTextWithCustomTextWatcher(R.id.editText5));
	        listEditText_.add(getEditTextWithCustomTextWatcher(R.id.editText6));
	        listEditText_.add(getEditTextWithCustomTextWatcher(R.id.editText7));
	        listEditText_.add(getEditTextWithCustomTextWatcher(R.id.editText8));
	        listEditText_.add(getEditTextWithCustomTextWatcher(R.id.editText9));
	        //listEditText_.add(getEditTextWithCustomTextWatcher(R.id.editText10));
	        
	        mStatus = (TextView) findViewById(R.id.status1);
	        mStatus.setText(message);
	        enableUi(false);
	    }
	    
	    protected IOIOLooper createIOIOLooper() {
			ioioThread = new IOIOThread();
			return ioioThread;
		}
	    
		private void enableUi(final boolean enable) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					for(int i = 0; i < listSeekBar_.size(); i++)
						listSeekBar_.get(i).setEnabled(enable);
				}
			});
		}
		
		private void enableUi(final boolean enable, final int location) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					listSeekBar_.get(location).setEnabled(enable);
				}
			});
		}
	
	    private EditText getEditTextWithCustomTextWatcher(int id){
	    	EditText editText = (EditText)findViewById(id);
	        editText.addTextChangedListener(new CustomTextWatcher(editText));
	        editText.setOnFocusChangeListener(new OnFocusChangeListener(){

				@TargetApi(9)
				@Override
				public void onFocusChange(View arg0, boolean arg1) {
					if(!arg1) {
						EditText editText = (EditText)arg0;
						if(editText.getText().toString().isEmpty())
							editText.setText("100");
						else{
							int value = Integer.parseInt(editText.getText().toString());
							if(value <= 0)
								value = 100;
							editText.setText(Integer.toString(value));
						}
					}
				}});
	        return editText;
	    }
	    
	}